#include<string>
#include<vector>
#include<array>
#include<unordered_map>
#include<algorithm>
#include<limits>
#include <stack>
#include<iostream>
#include<sstream>
#include<deque>
#define MOD 1000000007
class Solution {
public:
    int maxTaskAssign(std::vector<int>& tasks, std::vector<int>& workers, int pills, int strength) {
        std::sort(tasks.begin(), tasks.end());
        std::sort(workers.begin(), workers.end());
        int taLen = tasks.size();
        int wLen = workers.size();
        int ans = 0;
        for (int l = 0 ,r=std::min(taLen,wLen),m;l<=r;)
        {
            m=(l+r)/2;
            if (f(0,m-1,wLen-m,wLen-1,strength,pills,tasks,workers))
            {
                ans = m;
                l =m+1;
                
            }else
            {
                r = m-1;
            }
        }
        return ans;
    }
    bool f(int tl,int tr,int wl,int wr,int s,int pills,std::vector<int> & tasks,std::vector<int>& workers)
    {
        std::deque<int> q;
        int cnt = 0;
        for (int i = wl ,j=tl;i<=wr;i++)
        {
            for (;j<=tr&&tasks[j]<=workers[i];j++)
            {
                q.push_back(j);
            }
            if (!q.empty()&&tasks[q.front()]<=workers[i])
            {
                q.pop_front();
            }else
            {
                for (;j<=tr&&tasks[j]<=workers[i]+s;j++)
                {
                    q.push_back(j);
                }
                if (!q.empty())
                {
                    cnt++;
                    q.pop_back();
                }else
                {
                    return false;
                }
            }
        }
        return cnt<=pills;
    }
};